<script lang="ts" setup>
import { submitDepositDeduction } from '@/api/expense'
import { queryStoreOrderDetailInfo } from '@/api/order'
import { queryStoreOrderDetailInfoResponseData } from '@/api/order/types/order'
import { depositDeductionOperationType } from '@/types/enum'
import { getToken } from '@/utils/cache/cookies'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'

const dialogVisible = ref<boolean>(false)
const disabled = ref<boolean>(false)
const data = ref<null | queryStoreOrderDetailInfoResponseData>(null)
const open = async () => {
  getAdjustInfo()
  dialogVisible.value = true
}
const setData = (id: string) => {
  form.orderId = id
}
const getAdjustInfo = async () => {
  try {
    const res = await queryStoreOrderDetailInfo({
      token: getToken() ?? '',
      orderId: form.orderId
    })
    if (res.statusCode === '0') {
      data.value = res.data
    }
  } catch (error) {
    console.error(error)
  }
}
defineExpose({ open, setData })
const emits = defineEmits(['refresh'])
const form = reactive({
  operationType: '0',
  reason: '',
  amount: 0,
  orderId: '',
  remark: ''
})
const formRef = ref<FormInstance | null>(null)
const rules = reactive<FormRules>({
  operationType: [
    {
      required: true,
      message: '请选择抵扣类型',
      trigger: 'change'
    }
  ],
  reason: [
    {
      required: true,
      message: '请输入调整原因',
      trigger: 'blur'
    }
  ],
  amount: [
    {
      required: true,
      message: '请输入抵扣金额',
      trigger: 'blur'
    }
  ]
})
const handleClose = () => {
  formRef.value?.resetFields()
}
const cancel = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}
const submit = () => {
  if (form.remark) {
    form.operationType = '4'
  }
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const res = await submitDepositDeduction({
        token: getToken() ?? '',
        operationType: form.operationType as depositDeductionOperationType,
        reason: form.reason,
        amount: form.amount,
        orderId: form.orderId,
        remark: form.remark
      })
      if (res.statusCode === '0') {
        ElMessage.success(res.data)
        dialogVisible.value = false
        emits('refresh')
      }
    }
  })
}
const handleAmount = () => {
  form.amount =
    Number(form.amount) > Number(data.value?.remainDeposit)
      ? (data.value?.remainDeposit ?? 0)
      : form.amount
}
const handleTypeChange = () => {
  if (form.operationType === '2') {
    disabled.value = true
    if (data.value) {
      form.amount =
        data.value?.remainDeposit > data.value?.overdueAmount
          ? data.value?.overdueAmount
          : data.value?.remainDeposit
    }
  } else {
    disabled.value = false
  }
}
</script>

<template>
  <el-dialog
    title="押金抵扣"
    v-model="dialogVisible"
    width="650px"
    class="deposit-deduction-dialog"
    @close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
      <el-descriptions title="用户信息" :column="2">
        <el-descriptions-item label="用户手机号:">
          <span>{{ data?.userPhone }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="套餐类型:">
          <span>{{ data?.productType }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单:">
          <span>{{ data?.orderId }}</span> <span mt-10>({{ data?.productModel }})</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="订单信息" :column="2">
        <el-descriptions-item label="租赁天/次数:">
          <span>{{ data?.rentTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单总逾期天数:">
          <span>{{ data?.overDueTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="未支付逾期天数:">
          <span>{{ data?.unpaidTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="剩余时长/次数:">
          <span
            >{{ data?.remainTime
            }}<span v-if="data?.giftTime"
              >(含赠送<span>{{ data?.isLongTerm === 0 ? '时长' : '次数' }}</span
              >{{ data.giftTime }})</span
            ></span
          >
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="调整订单" :column="1">
        <el-descriptions-item>
          <el-form-item prop="operationType" label="调整类型:">
            <el-radio-group v-model="form.operationType" @change="handleTypeChange">
              <el-radio value="0">违章费</el-radio>
              <el-radio value="1">维修费</el-radio>
              <el-radio value="2">逾期费</el-radio>
              <el-radio value="3">赔偿费</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-form-item prop="remark" label="其他类型:">
            <el-input v-model="form.remark" placeholder="请输入需要扣费的类型" />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-form-item prop="amount" label="抵扣金额:">
            <el-input
              v-model="form.amount"
              placeholder="请输入需要抵扣的金额"
              @blur="handleAmount"
              :disabled="disabled"
            />
            <div class="text-[10px] text-grey leading-normal mt-5">
              <span v-if="form.operationType !== '2'"
                >当前用户剩余押金{{ data?.remainDeposit }}元
                <span class="is-reference" @click="form.amount = data?.remainDeposit!!">
                  全部填入 </span
                >,注意:扣除押金不可为负数
              </span>
              <span v-else
                >用户剩余押金{{ data?.remainDeposit }}元,当前套餐逾期时长为
                <span class="text-[#FF7880]">{{ data?.currentoverdueTime }}</span>
                ,共计<span>{{ data?.overdueAmount }}</span
                >元
              </span>
            </div>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-form-item prop="reason" label="调整原因:">
            <el-input
              v-model="form.reason"
              type="textarea"
              :autosize="{ minRows: 4 }"
              placeholder="请输入调整原因"
            />
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
